import { activeEffect } from "./effect"

//{target: {key: [fn]}}
let map = new Map()
function track(target, key) {
  let getTargets = map.get(target)
  if (!getTargets) {
    map.set(target, (getTargets = new Map()))
  }
  let fnSets = getTargets.get(key)
  if (!fnSets) {
    getTargets.set(key, (fnSets = new Set()))
  }
  fnSets.add(activeEffect)
}
function trigger(target, key) {
  const targetMap = map.get(target)
  if (targetMap) {
    const set = targetMap.get(key)
    if (set) {
      set.forEach(fn => fn())
    }
  }
}
export function reactive(obj) {
  return new Proxy(obj, {
    get(target, key) {
      const value = Reflect.get(target, key)
      track(target, key)
      // effects.add(activeEffect)
      return value
    },
    set(target, key, value) {
      const result = Reflect.set(target, key, value)
      trigger(target, key)
      return result
    },
    deleteProperty(target, key) {
      const result = Reflect.deleteProperty(target, key)
      return result
    }
  })
}
